package ipmanager.common;

public class BinaryNumber {

	private String binNumber;
	
	private int cantBits;

	/**
	 * Crea un nuevo BinayNumber con la cantidad de bits por parametro e
	 * inicializado en 0 (cero)
	 * 
	 * @param cantBits
	 */
	public BinaryNumber(int cantBits) {
		this.cantBits = cantBits;
		StringBuffer binNumberBuffer = new StringBuffer();
		for (int i = 0; i < cantBits; i++)
			binNumberBuffer.append("0");
		this.binNumber = binNumberBuffer.toString();
	}

	/**
	 * Crea un nuevo BinaryNumber con la cantidad de bits por parametro y un
	 * valor decimal por defecto
	 * 
	 * @param cantBits
	 * @param decNumber
	 */
	public BinaryNumber(int cantBits, String decNumber) {
		this.cantBits = cantBits;
		this.binNumber = Integer.toBinaryString(Integer.parseInt(decNumber));
		if (binNumber.length() < cantBits) {
			StringBuffer zeros = new StringBuffer();
			for (int k = 0; k < cantBits - binNumber.length(); k++)
				zeros.append("0");
			this.binNumber = zeros.toString() + this.binNumber;
		}
	}

	/**
	 * Retorna un numero binario que es la SUMA del actual y el pasado como
	 * parametro
	 * 
	 * @param anotherBinNumber
	 * @return binSum
	 */
	public BinaryNumber addOperation(BinaryNumber anotherBinNumber) {

		// Convierto a decimal
		int decPart1 = Integer.parseInt(this.binNumber, 2);
		int decPart2 = Integer.parseInt(anotherBinNumber.getBinNumber(), 2);
		int decSum = decPart1 + decPart2;

		// Convierto a binario
		String binSum = Integer.toBinaryString(decSum);

		// Si la parte tiene menos de 8 digitos, agregar 0's
		if (binSum.length() < cantBits) {
			StringBuffer zeros = new StringBuffer();
			for (int k = 0; k < cantBits - binSum.length(); k++)
				zeros.append("0");
			binSum = zeros.toString() + binSum;
		}

		String decSumS = Integer.toString(Integer.parseInt(binSum, 2));
		
		return new BinaryNumber(this.cantBits, decSumS);
	}

	
	/**
	 * Retorna el numero binario
	 * @return binNumber
	 */
	public String getBinNumber() {
		return this.binNumber;
	}
	

	/**
	 * Sobreescribo el metodo toString() devolviendo el binNumber
	 */
	public String toString() {
		return this.binNumber;
	}
	
}
